// error-monitor-sdk 主体实现
// 提供 SDK 的初始化、事件监听、手动上报、状态获取、销毁等核心功能
import { SDKConfig, ErrorInfo, PerformanceInfo, BehaviorInfo, EventListener, ErrorMonitorSDK } from './types';
import { ErrorMonitor } from './monitors/errorMonitor';
import { PerformanceMonitor } from './monitors/performanceMonitor';
import { BehaviorMonitor } from './monitors/behaviorMonitor';
import { Reporter } from './reporters/reporter';

export class ErrorMonitorSDKImpl implements ErrorMonitorSDK {
  private config: SDKConfig | null = null;
  private errorMonitor: ErrorMonitor | null = null;
  private performanceMonitor: PerformanceMonitor | null = null;
  private behaviorMonitor: BehaviorMonitor | null = null;
  private reporter: Reporter | null = null;
  private eventListeners: {
    error: EventListener[];
    performance: EventListener[];
    behavior: EventListener[];
  } = {
    error: [],
    performance: [],
    behavior: []
  };
  private isInitialized = false;

  // 初始化SDK
  public init(config: SDKConfig): void {
    if (this.isInitialized) {
      console.warn('Error monitor SDK: Already initialized');
      return;
    }

    // 验证配置
    if (!config.reportUrl) {
      throw new Error('reportUrl is required');
    }
    if (!config.appId) {
      throw new Error('appId is required');
    }

    this.config = {
      enableConsole: false,
      enablePerformance: true,
      enableBehavior: false,
      sampleRate: 1,
      maxCacheSize: 100,
      reportInterval: 5000,
      ...config
    };

    // 创建上报器
    this.reporter = new Reporter(this.config);

    // 创建错误监控器
    this.errorMonitor = new ErrorMonitor(
      this.config,
      (error: ErrorInfo) => {
        this.reporter?.reportError(error);
        this.emit('error', error);
      }
    );

    // 创建性能监控器
    if (this.config.enablePerformance) {
      this.performanceMonitor = new PerformanceMonitor(
        this.config,
        (performance: PerformanceInfo) => {
          this.reporter?.reportPerformance(performance);
          this.emit('performance', performance);
        }
      );
    }

    // 创建行为监控器
    if (this.config.enableBehavior) {
      this.behaviorMonitor = new BehaviorMonitor(
        this.config,
        (behavior: BehaviorInfo) => {
          this.reporter?.reportBehavior(behavior);
          this.emit('behavior', behavior);
        }
      );
    }

    // 初始化监控器
    this.errorMonitor.init();
    this.performanceMonitor?.init();
    this.behaviorMonitor?.init();

    // 监听页面卸载事件
    this.setupPageUnloadHandler();

    this.isInitialized = true;

    console.log('Error monitor SDK initialized successfully');
  }

  // 手动上报错误
  public reportError(error: Error | string, extra?: Record<string, any>): void {
    if (!this.isInitialized) {
      console.warn('Error monitor SDK: Not initialized');
      return;
    }

    this.errorMonitor?.reportError(error, extra);
  }

  // 手动上报性能信息
  public reportPerformance(performance: PerformanceInfo): void {
    if (!this.isInitialized) {
      console.warn('Error monitor SDK: Not initialized');
      return;
    }

    this.performanceMonitor?.reportPerformance(performance);
  }

  // 手动上报用户行为
  public reportBehavior(behavior: BehaviorInfo): void {
    if (!this.isInitialized) {
      console.warn('Error monitor SDK: Not initialized');
      return;
    }

    this.behaviorMonitor?.reportBehavior(behavior);
  }

  // 添加事件监听器
  public on(event: 'error' | 'performance' | 'behavior', listener: EventListener): void {
    this.eventListeners[event].push(listener);
  }

  // 移除事件监听器
  public off(event: 'error' | 'performance' | 'behavior', listener: EventListener): void {
    const listeners = this.eventListeners[event];
    const index = listeners.indexOf(listener);
    if (index > -1) {
      listeners.splice(index, 1);
    }
  }

  // 触发事件
  private emit(event: 'error' | 'performance' | 'behavior', data: ErrorInfo | PerformanceInfo | BehaviorInfo): void {
    this.eventListeners[event].forEach(listener => {
      try {
        listener(data);
      } catch (error) {
        console.warn('Error monitor SDK: Event listener error', error);
      }
    });
  }

  // 设置页面卸载处理器
  private setupPageUnloadHandler(): void {
    const handlePageUnload = () => {
      this.reporter?.sendBeacon();
    };

    // 监听页面卸载事件
    window.addEventListener('beforeunload', handlePageUnload);
    window.addEventListener('unload', handlePageUnload);
    window.addEventListener('pagehide', handlePageUnload);

    // 监听页面可见性变化
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'hidden') {
        this.reporter?.sendBeacon();
      }
    });
  }

  // 获取SDK状态
  public getStatus(): {
    isInitialized: boolean;
    config: SDKConfig | null;
    cacheStatus: {
      errorCount: number;
      performanceCount: number;
      behaviorCount: number;
    } | null;
  } {
    return {
      isInitialized: this.isInitialized,
      config: this.config,
      cacheStatus: this.reporter?.getCacheStatus() || null
    };
  }

  // 强制上报缓存数据
  public flush(): void {
    if (!this.isInitialized) {
      console.warn('Error monitor SDK: Not initialized');
      return;
    }

    this.reporter?.flush();
  }

  // 销毁SDK
  public destroy(): void {
    if (!this.isInitialized) {
      return;
    }

    // 销毁监控器
    this.errorMonitor?.destroy();
    this.performanceMonitor?.destroy();
    this.behaviorMonitor?.destroy();

    // 销毁上报器
    this.reporter?.destroy();

    // 清空事件监听器
    this.eventListeners.error = [];
    this.eventListeners.performance = [];
    this.eventListeners.behavior = [];

    // 重置状态
    this.config = null;
    this.errorMonitor = null;
    this.performanceMonitor = null;
    this.behaviorMonitor = null;
    this.reporter = null;
    this.isInitialized = false;

    console.log('Error monitor SDK destroyed');
  }
}

// 创建全局SDK实例
let globalSDK: ErrorMonitorSDKImpl | null = null;

// 创建SDK实例的工厂函数
export function createErrorMonitorSDK(): ErrorMonitorSDK {
  if (!globalSDK) {
    globalSDK = new ErrorMonitorSDKImpl();
  }
  return globalSDK;
}

// 获取全局SDK实例
export function getErrorMonitorSDK(): ErrorMonitorSDK | null {
  return globalSDK;
}

// 默认导出
export default createErrorMonitorSDK; 